package com.starblink.android.charles

import com.blankj.utilcode.util.LogUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException

/**
 * Mock数据拦截器
 */
class MockHttpInterceptor : Interceptor {
    companion object {
        const val TAG = "MockHttpInterceptor"
    }

    private val client = OkHttpClient.Builder()
        .addInterceptor(
            HttpLoggingInterceptor()
                .apply {
                    setLevel(HttpLoggingInterceptor.Level.BODY)
                }).build()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        // 生产环境 或者 Mock开关关闭，直接跳过
        if (CharlesManager.isPub?.invoke() != false || !CharlesManager.isMockPacketInfo()) {
            return chain.proceed(request)
        }

        var response: Response? = null
        var hasMockData: Boolean = false

        val call = client.newCall(
            Request.Builder()
                .url(
                    "${CharlesConfig.mockLog}?deviceId=${
                        CharlesManager.deviceId ?: ""
                    }&apiName=${
                        request.url.toString().substringAfterLast("/")
                    }"
                )
                .get().build()
        )
        hasMockData = try {
            val mockResponse = call.execute()
            if (!mockResponse.isSuccessful) {
                LogUtils.e(TAG, "获取Mock数据失败")
                false
            } else if (mockResponse.peekBody(Long.MAX_VALUE).string() == "400") {
                LogUtils.e(TAG, "无Mock数据")
                false
            } else {
                LogUtils.e(TAG, "成功获取Mock数据")
                response = Response.Builder()
                    .body(mockResponse.body)
                    .request(chain.request())
                    .protocol(Protocol.HTTP_2)
                    .message("Mock")
                    .code(200)
                    .build()
                true
            }
        } catch (e: IOException) {
            e.printStackTrace()
            LogUtils.e(TAG, e.toString())
            false
        } catch (e: Exception) {
            e.printStackTrace()
            LogUtils.e(TAG, e.toString())
            false
        }

        if (!hasMockData) {
            response = chain.proceed(request)
        }
        return response!!
    }
}